package com.itheima.service;

import com.itheima.dao.ContactMapper;
import com.itheima.pojo.Contact;
import com.itheima.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;
import java.util.Map;

/**
 * @author MaQing
 * @create 2022-05-10 14:54
 */
public class ContactService {
    public Boolean addContact(Contact contact) {
        SqlSession sqlSession = MybatisUtils.getSqlSession(true);
        ContactMapper mapper = sqlSession.getMapper(ContactMapper.class);
        int i = mapper.addContact(contact);
        MybatisUtils.close(sqlSession);
        return i>0;
    }

    public Contact findContactById(String id) {
        SqlSession sqlSession = MybatisUtils.getSqlSession(true);
        ContactMapper mapper = sqlSession.getMapper(ContactMapper.class);
        Contact contact= mapper.findContact(id);
        MybatisUtils.close(sqlSession);
        return contact;
    }


    public boolean updateContact(Contact contact) {
        SqlSession sqlSession = MybatisUtils.getSqlSession(true);
        ContactMapper mapper = sqlSession.getMapper(ContactMapper.class);
        int i = mapper.updateContact(contact);
        MybatisUtils.close(sqlSession);
        return i>0;

    }

    public boolean deleteContactById(String id) {
        SqlSession sqlSession = MybatisUtils.getSqlSession(true);
        ContactMapper mapper = sqlSession.getMapper(ContactMapper.class);
        int i = mapper.deleteContactById(id);
        MybatisUtils.close(sqlSession);
        return i>0;
    }

    public void deleteAll(String[] ids) throws Exception {
        //1.获取sqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession(true);
        //2.获取dao接口的代理类对象
        ContactMapper mapper = sqlSession.getMapper(ContactMapper.class);
        //3.处理业务,调用方法执行
        for(String id:ids){
            mapper.deleteContactById(id);
        }
        //4.关闭sqlSession
        MybatisUtils.close(sqlSession);
    }

    public List<Contact> findByCondition(Map<String, String> map) {
        //1.获取sqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //2.获取dao接口的代理类对象
        ContactMapper mapper = sqlSession.getMapper(ContactMapper.class);
        //3.调用方法执行
        List<Contact> list = mapper.findByCondition(map);
        //4.关闭sqlSession
        sqlSession.close();
        return list;
    }

    public List<Contact> findByPage(int pageSize, int currentPage) {
        //1.获取SqlSession对象
        SqlSession session = MybatisUtils.getSqlSession();
        //2.获取dao接口的代理类对象
        ContactMapper mapper = session.getMapper(ContactMapper.class);
        //3.处理业务,根据已知条件求出分页查询的必须条件
        // 分页的必须条件 起始索引 每页显示条数(已知)
        // 计算起始索引
        int startIndex = (currentPage-1)*pageSize;
        //4.调用方法执行
        List<Contact> list = mapper.findByPage(startIndex,pageSize);
        //5.关闭sqlSession
        MybatisUtils.close(session);
        return list;
    }
}






